package tom.server;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class SessionService extends RemoteServiceServlet {

	protected String dbName = "windmill";

	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	private static final long serialVersionUID = 1L;

	public void setSessionVar(String var, String value) {
		getSession().setAttribute(var, value);
	}

	public String getSessVar(String var) {
		Object obj = getSession().getAttribute(var);
		String value = null;
		if (obj != null)
			value = obj.toString();
		return value;
	}

	public HttpSession getSession() {
		return this.getThreadLocalRequest().getSession();
	}

	public static String[][] toStringArray(List<Object[]> result) {
		String[][] arr = null;
		if (result != null) {
			int r = result.size();
			if (r > 0) {
				int c = result.get(0).length;
				arr = new String[r][c];
				for (int i = 0; i < r; i++)
					for (int j = 0; j < c; j++) {
						Object obj = result.get(i)[j];
						if (obj != null)
							arr[i][j] = obj.toString();
					}
			}
		}
		return arr;
	}

	public Database getDatabase() {
		Database db = (Database) getSession().getAttribute(dbName);
		return db;
	}

	public int executeSQL(String sql) {
		return getDatabase().executeUpdate(sql);
	}

	public List<Object[]> executeQuery(String sql) {
		List<Object[]> list = new ArrayList<Object[]>();
		try {
			ResultSet res = getDatabase().executeQuery(sql);
			ResultSetMetaData rsmd = res.getMetaData();
			int columnCount = rsmd.getColumnCount();
			Object[] record = null;
			while (res.next()) {
				record = new Object[columnCount];
				for (int i = 0; i < columnCount; i++)
					record[i] = res.getObject(i + 1);
				list.add(record);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

}